/**
 * 认证相关工具函数
 */

import { aesEncrypt, aesDecrypt } from './crypto'

// Token 存储键名
const ACCESS_TOKEN_KEY = 'access_token'
const REFRESH_TOKEN_KEY = 'refresh_token'
const ACCESS_TOKEN_EXPIRES_KEY = 'access_token_expires'
const REFRESH_TOKEN_EXPIRES_KEY = 'refresh_token_expires'
const USER_KEY = 'user_info'
const PERMISSIONS_KEY = 'user_permissions'
const REMEMBER_USERNAME_KEY = 'remember_username'
const REMEMBER_PASSWORD_KEY = 'remember_password'
const REMEMBER_ME_KEY = 'remember_me'
const CURRENT_USERNAME_KEY = 'current_username'
const CURRENT_PASSWORD_KEY = 'current_password'

/**
 * 获取 Access Token
 */
export function getAccessToken(): string | null {
  return localStorage.getItem(ACCESS_TOKEN_KEY)
}

/**
 * 设置 Access Token
 */
export function setAccessToken(token: string): void {
  localStorage.setItem(ACCESS_TOKEN_KEY, token)
}

/**
 * 获取 Refresh Token
 */
export function getRefreshToken(): string | null {
  return localStorage.getItem(REFRESH_TOKEN_KEY)
}

/**
 * 设置 Refresh Token
 */
export function setRefreshToken(token: string): void {
  localStorage.setItem(REFRESH_TOKEN_KEY, token)
}

/**
 * 获取 Access Token 过期时间
 */
export function getAccessTokenExpires(): string | null {
  return localStorage.getItem(ACCESS_TOKEN_EXPIRES_KEY)
}

/**
 * 设置 Access Token 过期时间
 */
export function setAccessTokenExpires(expires: string): void {
  localStorage.setItem(ACCESS_TOKEN_EXPIRES_KEY, expires)
}

/**
 * 获取 Refresh Token 过期时间
 */
export function getRefreshTokenExpires(): string | null {
  return localStorage.getItem(REFRESH_TOKEN_EXPIRES_KEY)
}

/**
 * 设置 Refresh Token 过期时间
 */
export function setRefreshTokenExpires(expires: string): void {
  localStorage.setItem(REFRESH_TOKEN_EXPIRES_KEY, expires)
}

/**
 * 获取 Token (兼容旧版本)
 */
export function getToken(): string | null {
  return getAccessToken()
}

/**
 * 设置 Token (兼容旧版本)
 */
export function setToken(token: string): void {
  setAccessToken(token)
}

/**
 * 移除 Access Token
 */
export function removeAccessToken(): void {
  localStorage.removeItem(ACCESS_TOKEN_KEY)
}

/**
 * 移除 Refresh Token
 */
export function removeRefreshToken(): void {
  localStorage.removeItem(REFRESH_TOKEN_KEY)
}

/**
 * 移除 Token 过期时间
 */
export function removeTokenExpires(): void {
  localStorage.removeItem(ACCESS_TOKEN_EXPIRES_KEY)
  localStorage.removeItem(REFRESH_TOKEN_EXPIRES_KEY)
}

/**
 * 移除 Token (兼容旧版本)
 */
export function removeToken(): void {
  removeAccessToken()
}

/**
 * 获取用户信息
 */
export function getUser(): any {
  const userStr = localStorage.getItem(USER_KEY)
  return userStr ? JSON.parse(userStr) : null
}

/**
 * 设置用户信息
 */
export function setUser(user: any): void {
  localStorage.setItem(USER_KEY, JSON.stringify(user))
}

/**
 * 移除用户信息
 */
export function removeUser(): void {
  localStorage.removeItem(USER_KEY)
}

/**
 * 获取用户权限
 */
export function getPermissions(): string[] {
  const permissionsStr = localStorage.getItem(PERMISSIONS_KEY)
  return permissionsStr ? JSON.parse(permissionsStr) : []
}

/**
 * 设置用户权限
 */
export function setPermissions(permissions: string[]): void {
  localStorage.setItem(PERMISSIONS_KEY, JSON.stringify(permissions))
}

/**
 * 移除用户权限
 */
export function removePermissions(): void {
  localStorage.removeItem(PERMISSIONS_KEY)
}

/**
 * 清除所有认证信息
 */
export function clearAuth(): void {
  removeAccessToken()
  removeRefreshToken()
  removeTokenExpires()
  removeUser()
  removePermissions()
  clearCurrentSession() // 清除当前会话的登录信息
}

/**
 * 检查是否已登录
 */
export function isLoggedIn(): boolean {
  return !!getAccessToken()
}

/**
 * 检查 Access Token 是否过期
 */
export function isAccessTokenExpired(): boolean {
  const expires = getAccessTokenExpires()
  if (!expires) return true
  
  try {
    const expireTime = new Date(expires).getTime()
    const currentTime = new Date().getTime()
    // 提前5分钟判断为过期，避免临界时间问题
    return currentTime >= (expireTime - 5 * 60 * 1000)
  } catch {
    return true
  }
}

/**
 * 检查 Refresh Token 是否过期
 */
export function isRefreshTokenExpired(): boolean {
  const expires = getRefreshTokenExpires()
  if (!expires) return true
  
  try {
    const expireTime = new Date(expires).getTime()
    const currentTime = new Date().getTime()
    return currentTime >= expireTime
  } catch {
    return true
  }
}

/**
 * 检查是否需要刷新token
 */
export function shouldRefreshToken(): boolean {
  return !isRefreshTokenExpired() && isAccessTokenExpired()
}

/**
 * 检查用户是否有指定权限
 */
export function hasPermission(permission: string): boolean {
  const permissions = getPermissions()
  return permissions.includes(permission) || permissions.includes('*')
}

/**
 * 检查用户是否有任一权限
 */
export function hasAnyPermission(permissions: string[]): boolean {
  return permissions.some(permission => hasPermission(permission))
}

/**
 * 检查用户是否有所有权限
 */
export function hasAllPermissions(permissions: string[]): boolean {
  return permissions.every(permission => hasPermission(permission))
}

/**
 * 记住我功能相关函数
 */

/**
 * 设置记住我的用户名
 */
export function setRememberUsername(username: string): void {
  localStorage.setItem(REMEMBER_USERNAME_KEY, username)
}

/**
 * 获取记住我的用户名
 */
export function getRememberUsername(): string | null {
  return localStorage.getItem(REMEMBER_USERNAME_KEY)
}

/**
 * 设置记住我的密码（加密存储）
 */
export function setRememberPassword(password: string): void {
  try {
    const encryptedPassword = aesEncrypt(password)
    localStorage.setItem(REMEMBER_PASSWORD_KEY, encryptedPassword)
  } catch (error) {
    console.error('密码加密失败:', error)
    // 如果加密失败，不保存密码
  }
}

/**
 * 获取记住我的密码（解密返回）
 */
export function getRememberPassword(): string | null {
  try {
    const encryptedPassword = localStorage.getItem(REMEMBER_PASSWORD_KEY)
    if (!encryptedPassword) return null
    
    const decryptedPassword = aesDecrypt(encryptedPassword)
    return decryptedPassword
  } catch (error) {
    console.error('密码解密失败:', error)
    return null
  }
}

/**
 * 设置记住我状态
 */
export function setRememberMe(remember: boolean): void {
  localStorage.setItem(REMEMBER_ME_KEY, remember.toString())
}

/**
 * 获取记住我状态
 */
export function getRememberMe(): boolean {
  return localStorage.getItem(REMEMBER_ME_KEY) === 'true'
}

/**
 * 清除记住我的信息
 */
export function clearRememberMe(): void {
  localStorage.removeItem(REMEMBER_USERNAME_KEY)
  localStorage.removeItem(REMEMBER_PASSWORD_KEY)
  localStorage.removeItem(REMEMBER_ME_KEY)
}

/**
 * 设置当前会话的用户名（加密存储）
 */
export function setCurrentUsername(username: string): void {
  try {
    const encryptedUsername = aesEncrypt(username)
    localStorage.setItem(CURRENT_USERNAME_KEY, encryptedUsername)
  } catch (error) {
    console.error('用户名加密失败:', error)
  }
}

/**
 * 获取当前会话的用户名（解密返回）
 */
export function getCurrentUsername(): string | null {
  try {
    const encryptedUsername = localStorage.getItem(CURRENT_USERNAME_KEY)
    if (!encryptedUsername) return null
    
    const decryptedUsername = aesDecrypt(encryptedUsername)
    return decryptedUsername
  } catch (error) {
    console.error('用户名解密失败:', error)
    return null
  }
}

/**
 * 设置当前会话的密码（加密存储）
 */
export function setCurrentPassword(password: string): void {
  try {
    const encryptedPassword = aesEncrypt(password)
    localStorage.setItem(CURRENT_PASSWORD_KEY, encryptedPassword)
  } catch (error) {
    console.error('密码加密失败:', error)
  }
}

/**
 * 获取当前会话的密码（解密返回）
 */
export function getCurrentPassword(): string | null {
  try {
    const encryptedPassword = localStorage.getItem(CURRENT_PASSWORD_KEY)
    if (!encryptedPassword) return null
    
    const decryptedPassword = aesDecrypt(encryptedPassword)
    return decryptedPassword
  } catch (error) {
    console.error('密码解密失败:', error)
    return null
  }
}

/**
 * 清除当前会话的登录信息
 */
export function clearCurrentSession(): void {
  localStorage.removeItem(CURRENT_USERNAME_KEY)
  localStorage.removeItem(CURRENT_PASSWORD_KEY)
}

/**
 * 保存登录信息（记住我功能）
 */
export function saveLoginInfo(username: string, password: string, remember: boolean): void {
  // 总是保存当前会话的登录信息（用于密码验证）
  setCurrentUsername(username)
  setCurrentPassword(password)
  
  // 根据用户选择决定是否记住登录信息
  if (remember) {
    setRememberUsername(username)
    setRememberPassword(password)
    setRememberMe(true)
  } else {
    clearRememberMe()
  }
}

/**
 * 获取保存的登录信息
 */
export function getSavedLoginInfo(): { username: string; password: string; remember: boolean } | null {
  // 优先获取当前会话的登录信息
  const currentUsername = getCurrentUsername()
  const currentPassword = getCurrentPassword()
  
  if (currentUsername && currentPassword) {
    const remember = getRememberMe()
    return { username: currentUsername, password: currentPassword, remember }
  }
  
  // 如果没有当前会话信息，尝试获取记住的登录信息
  const remember = getRememberMe()
  if (!remember) return null
  
  const username = getRememberUsername()
  const password = getRememberPassword()
  
  if (!username || !password) return null
  
  return { username, password, remember }
}